<?php
/*
Plugin Name: 数据调用
Version: 2.0
Plugin URL: http://kller.cn/?post=70
Description: 实现emlog相关的数据调用功能。
ForEmlog: 5.x版本
Author: KLLER
Author Email: kller@foxmail.com
Author URL: http://kller.cn
*/
!defined('EMLOG_ROOT') && exit('access deined!');
define('KL_DATA_CALL_ROOT', EMLOG_ROOT.'/content/plugins/kl_data_call');
define('KL_DATA_CALL_CACHE_DIR', KL_DATA_CALL_ROOT.'/cache');

function kl_data_call()
{
	echo '<div class="sidebarsubmenu" id="kl_data_call"><a href="./plugin.php?plugin=kl_data_call">数据调用</a></div>';
}
addAction('adm_sidebar_ext', 'kl_data_call');

function kl_data_call_for_internal($id)
{
	echo kl_data_call_for_internal_value($id);
}

function kl_data_call_for_internal_value($id)
{
	$id = intval($id);
	$output = '';
	global $CACHE;
	$DB = MySql::getInstance();
	$CACHE->updateCache('options');
	$kl_data_call_info = Option::get('kl_data_call_'.$id);
	if(is_null($kl_data_call_info)) return $output;
	$moudle = unserialize($kl_data_call_info);
	$cache_file = KL_DATA_CALL_CACHE_DIR."/{$id}.php";
	$output .= file_exists($cache_file) && time() - filemtime($cache_file) < $moudle['cache_limit'] ? str_replace('<?php exit;//', '', @file_get_contents($cache_file)) : kl_data_call_main_fun($moudle);
	return $output;
}

function kl_data_call_breakLog($content, $lid, $isreadmore = false)
{
	$a = explode('[break]',$content,2);
	if(!empty($a[1]) && $isreadmore === true) $a[0].='<p><a href="'.Url::log($lid).'">阅读全文&gt;&gt;</a></p>';
	return $a[0];
}

function kl_data_call_main_fun($moudle)
{
	$code = stripslashes(base64_decode($moudle['code']));
	$output = kl_data_call_main_fun_for_preview($moudle, $code);
	$file_name = KL_DATA_CALL_CACHE_DIR.'/'.$moudle['did'].'.php';
	$fp = @fopen($file_name, 'w');
	fwrite($fp, '<?php exit;//'.$output);
	fclose($fp);
	return $output;
}

function kl_data_call_main_fun_for_preview_log($moudle, $code)
{
	$DB = MySql::getInstance();
	preg_match_all('%{(.*?)}%s', $code, $anArr, PREG_PATTERN_ORDER);
	$vArr = $anArr[1];

	$condition = '';
	if($moudle['custom_tailor'] != '')
	{
		$custom_tailor_arr = explode(',', $moudle['custom_tailor']);
		foreach($custom_tailor_arr as $k => $custom_tailor)
		{
			if(intval($custom_tailor) == 0)
			{
				unset($custom_tailor_arr[$k]);
			}else{
				$custom_tailor_arr[$k] = intval($custom_tailor);
			}
		}
		$custom_tailor_str = implode(',', $custom_tailor_arr);
		$condition .= "and a.gid in({$custom_tailor_str})";
	}else{
		if($moudle['filter'] == 1) $condition .= 'and a.top="y" ';
		if($moudle['filter'] == 2) $condition .= 'and a.top="n" ';
		if($moudle['is_include_img'] == 1) $condition .= 'and content not regexp "<img[^>]*src=[\'\"][^>]*/admin/[^>]*[\'\"][^>]*>" and content regexp "<img[^>]*src=[\'\"][^>]*[\'\"][^>]*>" ';
		if($moudle['is_include_img'] == 2) $condition .= 'and content not regexp "<img[^>]*src=[\'\"][^>]*[\'\"][^>]*>" ';
		if($moudle['nopwd'] == 1) $condition .= 'and a.password="" ';
		if($moudle['sort'] != -1) $condition .= $moudle['sort'] == 0 ? 'and a.sortid=-1 ' : 'and a.sortid='.$moudle['sort'].' ';
		if(isset($moudle['author']) && !empty($moudle['author'])) $condition .= "and c.uid={$moudle['author']} ";
	}
	$condition .= 'group by a.gid ';
	if($moudle['order_style'] == 0) $condition .= 'order by a.date desc ';
	if($moudle['order_style'] == 1) $condition .= 'order by cnum desc, a.gid desc ';
	if($moudle['order_style'] == 2) $condition .= 'order by a.views desc, a.gid desc ';
	if($moudle['order_style'] == 3) $condition .= 'order by rand() ';
	if($moudle['custom_tailor'] == '') $condition .= 'limit '.$moudle['start_num'].','.$moudle['dis_rows'];
	$sql = 'select a.gid as id, a.title, if(a.password!="", "", a.excerpt) as excerpt, if(a.password!="", "", a.content) as content, a.date, c.username as author, a.type, a.views, b.sortname as sort, count(d.cid) as cnum from '.DB_PREFIX.'blog a left join '.DB_PREFIX.'sort b on a.sortid=b.sid left join '.DB_PREFIX.'user c on c.uid=a.author left join '.DB_PREFIX.'comment d on d.gid=a.gid and d.hide="n" where a.hide="n" and type!="page" '.$condition;
	$result = $DB->query($sql);
	$dataArr = array();
	$auto_id = 1;
	while($row = $DB->fetch_array($result, MYSQL_ASSOC))
	{
		$row['auto_id'] = $auto_id;
		array_push($dataArr, $row);
		$auto_id++;
	}

	$output = '';
	if(count($dataArr) != 0)
	{
		$dataArrKey = array_keys($dataArr[0]);
		$evArr = array_intersect($vArr, $dataArrKey);
		$extra_arr = array('log_url', 'image', 'image_include_link', 'imageurl', 'title_without_link', 'excerpt_include_readmore', 'comment_count');
		foreach($extra_arr as $ev){
			if(in_array($ev, $vArr)) array_push($evArr, $ev);
		}
		foreach($dataArr as $dk => $data)
		{
			if($moudle['link_style'] == 0) $target = '';
			if($moudle['link_style'] == 1) $target = 'target="_blank"';
			if($moudle['link_style'] == 2) $target = 'target="_self"';
			$title = $data['title'];
			if(in_array('title_without_link', $vArr)) $data['title_without_link'] = $title;
			if(in_array('comment_count', $vArr)) $data['comment_count'] = $data['cnum'];
			$date_style_encode_arr = array('Y-n-j', 'Y-m-d', 'Y年n月j日', 'Y年m月d日', 'Y-n-j g:i', 'Y-m-d H:i', 'Y-n-j g:i:s', 'Y-m-d H:i:s', 'Y-n-j g:i:s l', 'Y-m-d H:i:s l');
			if(in_array('date', $vArr)) $data['date'] = date($date_style_encode_arr[$moudle['date_style']], $data['date']);
			$log_url = Url::log($data['id']);
			$blog_link_header = '<a href="'.$log_url.'" '.$target.' title="'.$title.'">';
			if(in_array('log_url', $vArr)) $data['log_url'] = $log_url;
			if(in_array('title', $vArr)) $data['title'] = $blog_link_header.$title.'</a>';
			$excerpt = $data['excerpt'];
			if(in_array('excerpt', $vArr)) $data['excerpt'] = empty($excerpt) ? kl_data_call_breakLog($data['content'],$data['id']) : $excerpt;
			if(in_array('excerpt_include_readmore', $vArr)) $data['excerpt_include_readmore'] = empty($excerpt) ? kl_data_call_breakLog($data['content'],$data['id'], true) : $excerpt .= '<p><a href="'.Url::log($data['id']).'">阅读全文&gt;&gt;</a></p>';
			$tmpArr = array_intersect(array('image', 'image_include_link', 'imageurl'), $vArr);
			if(!empty($tmpArr)){
				$search_pattern = '%<img[^>]*?src=[\'\"]((?:(?!\/admin\/|>).)+?)[\'\"][^>]*?>%s';
				preg_match($search_pattern, $data['content'], $kl_arr);
			}
			if(in_array('image', $vArr)) $data['image'] = isset($kl_arr[1]) ? $kl_arr[0] : '';
			if(in_array('image_include_link', $vArr)) $data['image_include_link'] = isset($kl_arr[1]) ? $blog_link_header.$kl_arr[0].'</a>' : '';
			if(in_array('imageurl', $vArr)) $data['imageurl'] = isset($kl_arr[1]) ? $kl_arr[1] : '';

			$codebak = $code;
			foreach($evArr as $ev)
			{
				if($ev == 'content') continue;
				$codebak = str_replace('{'.$ev.'}', $data[$ev], $codebak);
			}
			$output .= $codebak;
			$codebak = $code;
		}
	}
	return $output;
}

function kl_data_call_main_fun_for_preview_t($moudle, $code)
{
	$DB = MySql::getInstance();
	preg_match_all('%{(.*?)}%s', $code, $anArr, PREG_PATTERN_ORDER);
	$vArr = $anArr[1];

	$condition = '';
	if($moudle['custom_tailor'] != '')
	{
		$custom_tailor_arr = explode(',', $moudle['custom_tailor']);
		foreach($custom_tailor_arr as $k => $custom_tailor)
		{
			if(intval($custom_tailor) == 0)
			{
				unset($custom_tailor_arr[$k]);
			}else{
				$custom_tailor_arr[$k] = intval($custom_tailor);
			}
		}
		$custom_tailor_str = implode(',', $custom_tailor_arr);
		$condition .= "and a.id in({$custom_tailor_str})";
	}else{
		if($moudle['is_include_img'] == 1) $condition .= 'and a.img!="" ';
		if($moudle['is_include_img'] == 2) $condition .= 'and a.img="" ';
		if(isset($moudle['author']) && !empty($moudle['author'])) $condition .= "and b.uid={$moudle['author']} ";
	}
	if($moudle['order_style'] == 0) $condition .= 'order by a.date desc ';
	if($moudle['order_style'] == 1) $condition .= 'order by a.replynum desc, a.id desc ';
	if($moudle['order_style'] == 2) $condition .= 'order by rand() ';
	if($moudle['custom_tailor'] == '') $condition .= 'limit '.$moudle['start_num'].','.$moudle['dis_rows'];
	$sql = 'select a.id, a.content, a.img as imageurl, b.username as author, a.date, a.replynum from '.DB_PREFIX.'twitter a left join '.DB_PREFIX.'user b on b.uid=a.author where 1 '.$condition;
	$result = $DB->query($sql);
	$dataArr = array();
	$auto_id = 1;
	while($row = $DB->fetch_array($result, MYSQL_ASSOC))
	{
		$row['auto_id'] = $auto_id;
		array_push($dataArr, $row);
		$auto_id++;
	}

	$output = '';
	if(count($dataArr) != 0)
	{
		$dataArrKey = array_keys($dataArr[0]);
		$evArr = array_intersect($vArr, $dataArrKey);
		$extra_arr = array('thum_imageurl');
		foreach($extra_arr as $ev){
			if(in_array($ev, $vArr)) array_push($evArr, $ev);
		}
		foreach($dataArr as $dk => $data)
		{
			if(in_array('date', $vArr)){
				$date_style_encode_arr = array('Y-n-j', 'Y-m-d', 'Y年n月j日', 'Y年m月d日', 'Y-n-j g:i', 'Y-m-d H:i', 'Y-n-j g:i:s', 'Y-m-d H:i:s', 'Y-n-j g:i:s l', 'Y-m-d H:i:s l');
				$data['date'] = date($date_style_encode_arr[$moudle['date_style']], $data['date']);
			}
			if(in_array('imageurl', $vArr)) $data['imageurl'] = BLOG_URL.str_replace('thum-', '', $data['imageurl']);
			if(in_array('thum_imageurl', $vArr)) $data['thum_imageurl'] = BLOG_URL.$data['imageurl'];
			$codebak = $code;
			foreach($evArr as $ev)
			{
				$codebak = str_replace('{'.$ev.'}', $data[$ev], $codebak);
			}
			$output .= $codebak;
			$codebak = $code;
		}
	}
	return $output;
}

function kl_data_call_main_fun_for_preview_kl_album($moudle, $code)
{
	$DB = MySql::getInstance();
	preg_match_all('%{(.*?)}%s', $code, $anArr, PREG_PATTERN_ORDER);
	$vArr = $anArr[1];

	$condition = '';
	$kl_album_info = Option::get('kl_album_info');
	if(is_null($kl_album_info)) return '';
	$kl_album_info = unserialize($kl_album_info);
	$kl_album = Option::get('kl_album_'.$moudle['em_album']);
	if($moudle['em_album'] != 0){
		if(is_null($kl_album)){
			$condition = " and album={$moudle['em_album']} ";
			if($moudle['order_style'] == 0) $condition .= "order by id desc ";
		}else{
			$idStr = empty($kl_album) ? 0 : $kl_album;
			$condition = " and id in({$idStr}) ";
			if($moudle['order_style'] == 0) $condition .= "order by substring_index('{$idStr}', id, 1) ";
		}
	}else{
		if($moudle['order_style'] == 0) $condition .= "order by id desc ";
	}

	if($moudle['order_style'] == 1) $condition .= 'order by id desc ';
	if($moudle['order_style'] == 2) $condition .= 'order by rand() ';
	$condition .= 'limit '.$moudle['start_num'].','.$moudle['dis_rows'];
	$sql = 'select filename as thum_photo_url, description as photo_description, album as photo_album, addtime as photo_datetime from '.DB_PREFIX.'kl_album where 1 '.$condition;
	$result = $DB->query($sql);
	$dataArr = array();
	$auto_id = 1;
	while($row = $DB->fetch_array($result, MYSQL_ASSOC))
	{
		$row['auto_id'] = $auto_id;
		array_push($dataArr, $row);
		$auto_id++;
	}
	$output = '';
	if(count($dataArr) != 0)
	{
		$dataArrKey = array_keys($dataArr[0]);
		$evArr = array_intersect($vArr, $dataArrKey);
		$extra_arr = array('album_name', 'album_description', 'album_datetime', 'album_url', 'album_cover', 'photo_url');
		foreach($extra_arr as $ev){
			if(in_array($ev, $vArr)) array_push($evArr, $ev);
		}
		foreach($dataArr as $dk => $data)
		{
			if(in_array('album_datetime', $vArr)){
				$date_style_encode_arr = array('Y-n-j', 'Y-m-d', 'Y年n月j日', 'Y年m月d日', 'Y-n-j g:i', 'Y-m-d H:i', 'Y-n-j g:i:s', 'Y-m-d H:i:s', 'Y-n-j g:i:s l', 'Y-m-d H:i:s l');
				$data['album_datetime'] = date($date_style_encode_arr[$moudle['date_style']], $data['photo_album']);
			}
			if(in_array('photo_datetime', $vArr)) $data['photo_datetime'] = date($date_style_encode_arr[$moudle['date_style']], $data['photo_datetime']);
			if(in_array('thum_photo_url', $vArr)) $data['thum_photo_url'] = BLOG_URL.substr($data['thum_photo_url'], 3);
			if(in_array('photo_url', $vArr)) $data['photo_url'] = BLOG_URL.str_replace('thum-', '', substr($data['thum_photo_url'], 3));
			foreach($kl_album_info as $kl_album){
				if($kl_album['addtime'] == $data['photo_album']){
					if(in_array('album_name', $vArr)) $data['album_name'] = $kl_album['name'];
					if(in_array('album_description', $vArr)) $data['album_description'] = $kl_album['description'];
					if(in_array('album_url', $vArr)) $data['album_url'] = BLOG_URL.'?plugin=kl_album&album='.$kl_album['addtime'];
					if(in_array('album_cover', $vArr)){
						$data['album_cover'] = '';
						if(isset($kl_album['head'])){
							$iquery = $DB->query("SELECT * FROM ".DB_PREFIX."kl_album WHERE id={$kl_album['head']}");
							if($DB->num_rows($iquery) > 0){
								$irow = $DB->fetch_array($iquery);
								$data['album_cover'] = BLOG_URL.substr($irow['filename'], 3);
							}
						}
						if(empty($data['album_cover'])){
							$iquery = $DB->query("SELECT * FROM ".DB_PREFIX."kl_album WHERE 1 ".$condition);
							if($DB->num_rows($iquery) > 0){
								$irow = $DB->fetch_array($iquery);
								$data['album_cover'] = BLOG_URL.substr($irow['filename'], 3);
							}
						}
					}
				}
			}
			$codebak = $code;
			foreach($evArr as $ev)
			{
				$codebak = str_replace('{'.$ev.'}', $data[$ev], $codebak);
			}
			$output .= $codebak;
			$codebak = $code;
		}
	}
	return $output;
}

function kl_data_call_main_fun_for_preview($moudle, $code){
	$kl_t_array = array('文章调用', '微语调用', 'EM相册调用');
	$kl_t = isset($moudle['kl_t']) && in_array($moudle['kl_t'], array_keys($kl_t_array)) ? $moudle['kl_t'] : 0;
	if($kl_t == 1){
		return kl_data_call_main_fun_for_preview_t($moudle, $code);
	}elseif($kl_t == 2){
		return kl_data_call_main_fun_for_preview_kl_album($moudle, $code);
	}else{
		return kl_data_call_main_fun_for_preview_log($moudle, $code);
	}
}